package com.typing.alarm.activity;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.ToggleButton;

import com.typing.alarm.R;
import com.typing.alarm.database.DBManager;
import com.typing.alarm.receiver.TypingAlarmReceiver;
import com.typing.alarm.service.ITypingAlarmService;
import com.typing.alarm.service.TypingAlarmService;
import com.typing.alarm.util.DialogUtil;
import com.typing.alarm.value.TypingAlarmVO;

public class AlarmRegisterActivity extends Activity {
	
	public ServiceConnection conn=null;

	private GregorianCalendar cal;
	private TimePicker time;
	private EditText alarmName,typingText,typingSpeed;
	private ToggleButton useYn,repeatYn;
	private boolean[] repeatDay;
	private Uri ringtoneUri;
	private Button ringtone,choose,save,cancel;
	int hour,min;
	
	private DBManager dbMgr;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.alarm_register); 
        
        cal = new GregorianCalendar();
        repeatDay = new boolean[7];
        choose = (Button)findViewById(R.id.choose_day);
        choose.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showChooseDay();
			}
		});
        
        ringtone = (Button)findViewById(R.id.ringtone);
        ringtone.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				moveRingtone();
			}
		});
        
        save = (Button)findViewById(R.id.save_alarm);
        save.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//setAlarm();
				saveAlarm();
			}
		});
        
        Button cancel = (Button)findViewById(R.id.cancel_alarm);
        cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				cancel();
			}
		});
        
        
        
        time = (TimePicker)findViewById(R.id.alarm_time);
        time.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
        time.setCurrentMinute(cal.get(Calendar.MINUTE));
        time.setOnTimeChangedListener(new OnTimeChangedListener() {
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
				// TODO Auto-generated method stub
				Log.d("AlarmRegisterActivity","onTimeChanged " + cal.get(cal.YEAR) + " " +cal.get(cal.MONTH)+ " " +cal.get(cal.DATE) + " " + hourOfDay + " " + minute);
				hour = hourOfDay;
				min = minute;				
			}
		});
        
        alarmName = (EditText)findViewById(R.id.alarm_name);
		typingText = (EditText)findViewById(R.id.alarm_typing_text);
		typingSpeed = (EditText)findViewById(R.id.alarm_typing_speed);
		alarmName.setOnFocusChangeListener(new OnFocusChangeListener(){		
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(!hasFocus){
					hideSoftKeyboard(v);
				}
			}
		});
		typingText.setOnFocusChangeListener(new OnFocusChangeListener(){		
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(!hasFocus){
					hideSoftKeyboard(v);
				}
				
			}
		});
		typingSpeed.setOnFocusChangeListener(new OnFocusChangeListener(){		
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(!hasFocus){
					hideSoftKeyboard(v);
				}
				
			}
		});
        conn=new ServiceConnection() {
        	@Override
        	public void onServiceConnected(ComponentName name, IBinder service){  
        		// TODO Auto-generated catch block
        		ITypingAlarmService myService = ITypingAlarmService.Stub.asInterface(service);
        		try {        			
        			myService.refleshAlarm();        			
				} catch (RemoteException e) {					
					e.printStackTrace();
				}
        	}
        	@Override
        	public void onServiceDisconnected(ComponentName name){
        		// TODO Auto-generated catch block
        	}			
        };
    }
    public void saveAlarm(){
    	dbMgr = new DBManager(this);
		dbMgr.open();
		dbMgr.addAlarmInfo(getAlarmVO());
		dbMgr.close();		
		//startService(new Intent(this,TypingAlarmService.class));		            	
		bindService(new Intent(this,TypingAlarmService.class) ,conn, Context.BIND_AUTO_CREATE);			
		startActivity(new Intent(this,AlarmListActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
    }
    public TypingAlarmVO getAlarmVO(){
    	alarmName = (EditText)findViewById(R.id.alarm_name);
		typingText = (EditText)findViewById(R.id.alarm_typing_text);
		typingSpeed = (EditText)findViewById(R.id.alarm_typing_speed);
		
		useYn = (ToggleButton)findViewById(R.id.alarm_use_yn);
		repeatYn = (ToggleButton)findViewById(R.id.alarm_repeat_yn);
		
    	TypingAlarmVO data = new TypingAlarmVO();
    	String time1 = hour > 9 ? ""+hour : "0"+hour;
    	String time2 = min > 9 ? ""+min : "0"+min;
    	data.setAlarmTime(time1 + ":"+ time2);
		data.setAlarmName(alarmName.getText().toString());
		data.setTypingText(typingText.getText().toString());
		data.setTypingSpeed(typingSpeed.getText().toString());
		if(ringtoneUri != null){
			data.setRingSound(ringtoneUri.toString());
		}
		data.setRepeatDay(repeatDay);		
		data.setUseYn(useYn.isChecked() ? "Y" : "N");
		data.setRepeatYn(repeatYn.isChecked() ? "Y" : "N");
		
		return data;
    }
    public void cancel(){
    	startActivity(new Intent(this,AlarmListActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
    }
    public void setRepeatDay(int index,boolean isChecked){
    	repeatDay[index] = isChecked;
    }
    public boolean[] getRepeatDay(){
    	return this.repeatDay;
    }    
    public void showChooseDay(){
    	DialogUtil.showChooseDay(this);
    }   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    	switch(requestCode){
    		case 0 : 
    				ringtoneUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
    				Ringtone alarmRingtone = RingtoneManager.getRingtone(this, ringtoneUri);    				
    				ringtone.setText(alarmRingtone.getTitle(this));
    				break;
    	}
    }
    
    public void moveRingtone(){
    	Intent i = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
    	startActivityForResult(i, 0);
    }
    
    public void hideSoftKeyboard(View input){
    	//InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);         
        //imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
    }
}